package com.sky.component;

import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageQueueTopicConstant;
import com.sky.entity.VoucherOrder;
import com.sky.mapper.VoucherMapper;
import com.sky.mapper.VoucherOrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.MessageModel;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @Author: invictusQAQ
 * @Date: 2023-09-09-10:49
 * @Description: 处理秒杀券下单
 */
@Component
@Slf4j
@RocketMQMessageListener(topic = MessageQueueTopicConstant.SECKILL_VOUCHER_TOPIC,consumerGroup = "${rocketmq.consumer.group}",
        selectorType = SelectorType.TAG,selectorExpression = MessageQueueTopicConstant.SECKILL_VOUCHER_TAG,messageModel = MessageModel.CLUSTERING)
public class SeckillMsgListener implements RocketMQListener<MessageExt> {

    @Autowired
    private VoucherOrderMapper voucherOrderMapper;
    @Autowired
    private VoucherMapper voucherMapper;

    @Override
    @Transactional
    public void onMessage(MessageExt messageExt) {
        VoucherOrder voucherOrder= JSONObject.parseObject(messageExt.getBody(),VoucherOrder.class);

        log.info("接收到下单消息{}",voucherOrder);

        Long userId= voucherOrder.getUserId();
        Long voucherOrderId= voucherOrder.getId();
        Long voucherId=voucherOrder.getVoucherId();

        //设置id为空，因为该id为snowflake生成传入，数据库内一定不存在
        //通过MySQL判断一人一单和库存超卖（理论上已经通过Redis验证可以不需要）
        voucherOrder.setId(null);
        List<VoucherOrder> list = voucherOrderMapper.getVoucherOrder(voucherOrder);
        if(list!=null&&list.size()>0){
            log.info("请不要重复下单");
            return;
        }
        //扣减库存
        log.info("扣减库存");
        Integer result= voucherMapper.decrSeckillVoucher(voucherId);
        if(result!=null&&result<=0){
            log.info("秒杀券已售罄");
            return;
        }
        //MySQL添加秒杀券订单
        voucherOrder.setId(voucherOrderId);
        log.info("添加订单");
        voucherOrderMapper.addVoucherOrder(voucherOrder);
    }
}
